package org.wendu.wdoa.service.impl;

import org.wendu.wdoa.common.Utils;
import org.wendu.wdoa.common.page.Page;
import org.wendu.wdoa.dao.RoleDao;
import org.wendu.wdoa.dto.MenuDto;
import org.wendu.wdoa.dto.RoleQueryDto;
import org.wendu.wdoa.model.Fun;
import org.wendu.wdoa.model.Role;
import org.wendu.wdoa.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;


    @Override
    public Page<Role> getRolePage(RoleQueryDto dto) {
        return Utils.getPage(dto,()->roleDao.findRoleList(dto));

    }

    @Override
    public void setRoleFuns(Integer ro_id, Integer[] funIds) {
        roleDao.deleteFunsByRoleId(ro_id); //根据角色编号删除表t_rm中的角色权限数据
        roleDao.insertRoleFuns(ro_id,funIds);
    }


    @Override
    public List<MenuDto> getRoleFunList(Integer roleId) {
        List<Fun> funList = roleDao.findRoleFunList(roleId);

        List<MenuDto> mainList = new ArrayList<>();  //主菜单集合

        MenuDto currentMainMenu = null;  //当前主菜单
        for (Fun fun: funList){
            if (currentMainMenu == null || !fun.getP_id().equals(currentMainMenu.getMenuId())){
                /*
                 * 如果当前主菜单不存在或者当前遍历的数据中的父菜单编号与当前主菜单编号不一致
                 * 应当新创建一个当前主菜单并放入主菜单集合
                 */
                currentMainMenu = new MenuDto();//内部类不能访问外部的局部变量
                currentMainMenu.setMenuId(fun.getP_id()); // 设置主菜单编号
                currentMainMenu.setMenuName(fun.getP_name());  //设置主菜单名称
                currentMainMenu.setChildren(new ArrayList<MenuDto>()); // 设置子菜单集合



                mainList.add(currentMainMenu);
            }
            //当前遍历数据中的子菜单部分分离出来封装到MenuDto对象中，并将该对象放入当前主菜单的子菜单集合中
            MenuDto subMenu = new MenuDto();
            subMenu.setMenuId(fun.getF_id());
            subMenu.setMenuName(fun.getF_name());
            subMenu.setSelected(fun.isSelected());
            currentMainMenu.getChildren().add(subMenu);


        }

        return mainList;
    }

    @Override
    public void deleteUserById(Integer roleId) {
        roleDao.deleteUserByRoleId(roleId);
    }

    @Override
    public void deleteMany(Integer[] roId) {
        for (int ros:roId) {
            roleDao.deleteUserByRoleId(ros);
        }
    }

    @Override
    public void insertUser(Integer roId, String roName) {
        roleDao.insertUser(roId,roName);
    }

    @Override
    public void updateOldUser(Integer ro_id, String ro_name) {
        roleDao.changeUser(ro_id,ro_name);
    }
}
